//
//  Account.m
//  帮惠Mall
//
//  Created by reew on 2017/9/19.
//  Copyright © 2017年 reew. All rights reserved.
//

#import "Account.h"
#define kAccountFileName @"account"
@implementation Account
static Account *account;
+(instancetype)sharedAccount{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        NSString *filePah = [self filePathForDocuments:kAccountFileName];
        //解档对象
        account = [NSKeyedUnarchiver unarchiveObjectWithFile:filePah];
        //如果解档文件不存在，对象为空
        if (!account) {
            account = [[Account alloc] init];
        }
    });
    
    return account;
}

- (void)saveLoginInfo:(NSDictionary *)info{
    self.adminNo = info[@"adminNo"];
    self.name = info[@"name"];
    self.companyFlag = info[@"companyFlag"];
    //保存到物理文件中
    [NSKeyedArchiver archiveRootObject:account toFile:[self getPath:kAccountFileName]];

}
- (BOOL)isLogin{
    if (self.adminNo ==nil) {
        return NO;
    }else{
        return YES;
    }
}

-(void)logout{
    self.adminNo = nil;
    self.name = nil;
    self.companyFlag = nil;
    //删除归档信息
    NSString *filePath = [self getPath:kAccountFileName];
    //删除文件
    [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
}
#pragma mark - coding

-(id)initWithCoder:(NSCoder *)aDecoder{
    self = [super init];
    if (self) {
        self.adminNo = [aDecoder decodeObjectForKey:@"adminNo"];
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.companyFlag = [aDecoder decodeObjectForKey:@"companyFlag"];
    }
    return self;
}
- (void)encodeWithCoder:(NSCoder *)coder
{
    [coder encodeObject:self.adminNo forKey:@"adminNo"];
    [coder encodeObject:self.name forKey:@"name"];
    [coder encodeObject:self.name forKey:@"companyFlag"];
}
+(NSString *)filePathForDocuments:(NSString *)fileName{
    //归档的文件路径
    NSString *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *filePath = [documents stringByAppendingPathComponent:fileName];
    return filePath;
}
- (NSString *)getPath:(NSString *)fileName{
    //归档的文件路径
    NSString *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *filePath = [documents stringByAppendingPathComponent:fileName];
    return filePath;
}
@end
